package com.mall.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.R;
import com.mall.common.RedisClient;
import com.mall.entity.SmoothMallProduct;
import com.mall.mapper.SmoothMallProductMapper;
import com.mall.service.SmoothMallProductService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.compress.utils.IOUtils;
import org.jetbrains.annotations.TestOnly;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmoothMallProductServiceImpl extends ServiceImpl<SmoothMallProductMapper, SmoothMallProduct> implements SmoothMallProductService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    RedisClient redisClient;
    //存储普通文件
    @Value("${minio.bucket.files}")
    private String bucket_mall;

    @Override
    public String uploadMall(File file) {
        String absolutePath = file.getAbsolutePath();
        //获取文件名
        String name = file.getName();
        //获取扩展名
        String extension = name.substring(name.lastIndexOf("."));
        String mimeType = getMimeType(extension);
        //获取文件默认存储目录路径 年/月/日/
        String defaultFolderPath = getDefaultFolderPath();
        String fileMd5 = getFileMd5(file);
        //存储路径+文件名
        fileMd5=defaultFolderPath+fileMd5+extension;
        boolean b = addMediaFilesToMinIO(absolutePath, mimeType, bucket_mall, fileMd5);
        if (b){
            String jpg=bucket_mall+"/"+fileMd5;
            return jpg;
        }
        return null;
    }
    /**
     * 将文件上传到minio
     *
     * @param localFilePath 文件本地路径
     * @param mimeType      媒体类型
     * @param bucket        桶
     * @param objectName    对象名
     * @return
     */
    public boolean addMediaFilesToMinIO(String localFilePath, String mimeType, String bucket, String objectName) {
        try {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucket)//桶
                    .filename(localFilePath) //指定本地文件路径
                    .object(objectName)//对象名 放在子目录下
                    .contentType(mimeType)//设置媒体文件类型
                    .build();
            //上传文件
            minioClient.uploadObject(uploadObjectArgs);
            log.debug("上传文件到minio成功,bucket:{},objectName:{},错误信息:{}", bucket, objectName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件出错,bucket:{},objectName:{},错误信息:{}", bucket, objectName, e.getMessage());
        }
        return false;
    }
    //获取文件默认存储目录路径 年/月/日
    private String getDefaultFolderPath() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String folder = sdf.format(new Date()).replace("-", "/") + "/";
        return folder;
    }
    //根据扩展名获取mimeType
    private String getMimeType(String extension) {
        if (extension == null) {
            extension = "";
        }
        //根据扩展名取出mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;//通用mimeType，字节流
        if (extensionMatch != null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;

    }
    //获取文件的md5
    private String getFileMd5(File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String fileMd5 = DigestUtils.md5Hex(fileInputStream);
            return fileMd5;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //从minio中下载文件
    @Override
    public File downloadFileFromMinIO(String bucket, String objectName) {
        //临时文件
        File minioFile = null;
        FileOutputStream outputStream = null;
        try {
            InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .build());
            //创建临时文件
            minioFile = File.createTempFile("minio", ".merge");
            outputStream = new FileOutputStream(minioFile);
            IOUtils.copy(stream, outputStream);
            return minioFile;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public SmoothMallProduct getByIdWithPassThrough(Integer id) {
//        SmoothMallProduct smoothMallProduct = redisClient.selectWithPassThrough("product:", id, SmoothMallProduct.class, this::getById, 30L, TimeUnit.MINUTES);
        SmoothMallProduct smoothMallProduct = redisClient.selectWithBreakDown("product:hot:", id, SmoothMallProduct.class, this::getById, 30L, TimeUnit.MINUTES);
        return smoothMallProduct;
    }
}

